package org.jingouzhui.domain.strategy.service.raffle;

import lombok.extern.slf4j.Slf4j;
import org.jingouzhui.domain.strategy.model.valboj.RuleTreeVO;
import org.jingouzhui.domain.strategy.model.valboj.StrategyAwardRuleModelVO;
import org.jingouzhui.domain.strategy.model.valboj.StrategyAwardStockKeyVO;
import org.jingouzhui.domain.strategy.repository.IStrategyRepository;
import org.jingouzhui.domain.strategy.service.AbstractRaffleStrategy;
import org.jingouzhui.domain.strategy.service.armory.IStrategyDispatch;
import org.jingouzhui.domain.strategy.service.rule.chain.ILogicChain;
import org.jingouzhui.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import org.jingouzhui.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import org.jingouzhui.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.jingouzhui.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @description:
 * @author: jingouzhui
 * @date: 2025/4/27 17:15
 */
@Slf4j
@Service
public class DefaultRaffleStrategy extends AbstractRaffleStrategy {

    @Resource
    private DefaultLogicFactory logicFactory;

    public DefaultRaffleStrategy(IStrategyRepository strategyRepository, IStrategyDispatch strategyDispatch, DefaultLogicChainFactory defaultLogicChainFactory, DefaultTreeFactory defaultTreeFactory) {
        super(strategyRepository, strategyDispatch,defaultLogicChainFactory,defaultTreeFactory);
    }

    @Override
    public DefaultLogicChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId) {
        ILogicChain logicChain = defaultLogicChainFactory.openLogicChain(strategyId);
        return logicChain.logic(userId, strategyId);
    }

    @Override
    public DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Integer awardId) {
        StrategyAwardRuleModelVO strategyAwardRuleModelVO = strategyRepository.queryRuleModelByStrategyIdAndAwardId(strategyId, awardId);
        if (Objects.isNull(strategyAwardRuleModelVO)) {
            return DefaultTreeFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .build();
        }
        //ruleModel对应的就是规则树的treeId
        RuleTreeVO ruleTreeVO = strategyRepository.queryRuleTreeVOByTreeId(strategyAwardRuleModelVO.getRuleModels());
        IDecisionTreeEngine decisionTreeEngine = defaultTreeFactory.openLogicTree(ruleTreeVO);
        return  decisionTreeEngine.process(userId,strategyId,awardId);
    }

    @Override
    public StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException {
        return strategyRepository.takeQueueValue();
    }


    @Override
    public void updateStrategyAwardStock(Long strategyId, Integer awardId) {
        strategyRepository.updateStrategyAwardStock(strategyId, awardId);
    }

}
